import { createRouter, createWebHashHistory } from 'vue-router'
import { h } from 'vue'
import store from '@/store'

const Layout = () => import('@/views/Layout.vue')
const Home = () => import('@/views/home')
const Category = () => import('@/views/category')
const SubCategory = () => import('@/views/category/sub.vue')
const Product = () => import('@/views/goods')
const Cart = () => import('@/views/cart')

const Pay = () => import('@/views/member/pay/index.vue')
const Checkout = () => import('@/views/member/pay/checkout.vue')
const PayResult = () => import('@/views/member/pay/result')

const Login = () => import('@/views/login/index.vue')
const LoginCallback = () => import('@/views/login/callback.vue')

const MemberLayout = () => import('@/views/member/Layout')
const MemberHome = () => import('@/views/member/home')
const MemberOrder = () => import('@/views/member/order')
const MemberOrderDetail = () => import('@/views/member/order/detail')

const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '/',
        name: 'home',
        component: Home
      },
      {
        path: '/category/:id',
        name: 'category',
        component: Category
      },
      {
        path: '/category/sub/:id',
        name: 'subCategory',
        component: SubCategory
      },
      {
        path: '/product/:id',
        name: 'product',
        component: Product
      },
      { path: '/cart', component: Cart },
      { path: '/member/checkout', component: Checkout },
      { path: '/member/pay', component: Pay },
      { path: '/pay/callback', component: PayResult },
      {
        path: '/member',
        component: MemberLayout,
        children: [
          { path: '/member', component: MemberHome },
          // { path: '/member/order', component: MemberOrder }
          // { path: '/member/order/:id', component: MemberOrderDetail }
          {
            path: '/member/order',
            // 创建一个RouterView容器形成嵌套关系
            component: { render: () => h(<RouterView />) },
            children: [
              { path: '', component: MemberOrder },
              { path: ':id', component: MemberOrderDetail }
            ]
          }
        ]
      }
    ]
  },

  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/login/callback',
    name: 'callback',
    component: LoginCallback
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  linkActiveClass: 'active',
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve({ left: 0, top: 0 })
      }, 200)
    })
  }
})
// 前置导航守卫
router.beforeEach((to, from, next) => {
  // 需要登录的路由：地址是以 /member 开头
  const { userInfo } = store.state.user
  if (!userInfo.token && to.path.startsWith('/member')) {
    return next('/login?redirectUrl=' + encodeURIComponent(to.fullPath))
  }
  next()
})
export default router
